package controllers

import (
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"math"
	"novel_website_db/cache"
	"novel_website_db/models"
)

type RecordController struct {
	beego.Controller
}

// page
type PageMsg struct {
	Code    int         `json:"code"`
	Msg     string      `json:"msg"`
	Data    interface{} `json:"data"`
	Page    int         `json:"page"`
	Size    int         `json:"size"`
	Count   int64       `json:"count"`
	Sumpage int         `json:"sumpage"`
}

// 分页
func (c *RecordController) ListPage() {
	//跨域
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")

	//分页
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 5)
	//计算总数据
	var count int64
	models.DB.Model(&models.Record{}).Count(&count)
	//计算总页数
	sumpage := int(math.Ceil(float64(count) / float64(size)))
	if page > sumpage {
		page = sumpage
	}
	//计算偏移量
	offset := (page - 1) * size

	//定义id
	var MyNovelId []interface{}
	//接收id
	userId, _ := c.GetInt("user_id")
	models.DB.Model(&models.Record{}).Select("novel_id").Where("user_id = ?", userId).Find(&MyNovelId)

	//接收结构体
	var novel []models.Novel
	models.DB.Where("id in (?)", MyNovelId).Offset(offset).Limit(size).Find(&novel)

	res := PageMsg{
		Code:    200,
		Msg:     "查询成功",
		Data:    novel,
		Page:    page,
		Size:    size,
		Count:   count,
		Sumpage: sumpage,
	}
	c.Data["json"] = res
	c.ServeJSON()
	return

}

// 阅读列表
func (c *RecordController) List() {
	//接收数据
	cacheData := cache.Rdb.Get(cache.Ctx, "record_list").Val()
	var novel []models.Novel

	if cacheData == "" {
		var MyNovelId []interface{}
		userId, _ := c.GetInt("user_id")
		models.DB.Model(&models.Record{}).Select("novel_id").Where("user_id =?", userId).Find(&MyNovelId)
		models.DB.Where("id in (?)", MyNovelId).Find(&novel)

		jsonData, _ := json.Marshal(&novel)
		cache.Rdb.Set(cache.Ctx, "record_list", jsonData, 0)

	} else {
		json.Unmarshal([]byte(cacheData), &novel)
	}

	res := Response{
		Code: 200,
		Msg:  "查询成功",
		Data: novel,
	}
	c.Data["json"] = res
	c.ServeJSON()
	return

}

// 删除
func (c *RecordController) Del() {
	//接收id
	id, _ := c.GetInt("id")
	//接收结构体
	var record models.Record
	models.DB.Where("id =?", id).First(&record)
	//判断状态
	if record.Status == "已完成" {
		res := Response{
			Code: 500,
			Msg:  "已完成阅读的记录禁止删除",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
		return
	}

	//实例化数据
	record.ID = uint(id)
	//调用方法，实现删除
	if record.Del(id) != nil {
		res := Response{
			Code: 500,
			Msg:  "删除失败",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
		return
	}

	res := Response{
		Code: 200,
		Msg:  "删除成功",
		Data: nil,
	}
	c.Data["json"] = res
	c.ServeJSON()
	return

}
